package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-14
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;



    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从阿里云同步设备列表
     */
    @Override
    public void syncProductList() {
        // 1.访问阿里云IOT平台获取所有产品列表
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setPageSize(100);
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryProductListResponse response;
        try {
            response = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            throw new BaseException("调用阿里云IOT平台查询失败");
        }

        // 判断调用阿里云IOT平台的结果是否是失败
        if (!response.getBody().getSuccess()) {
            throw new BaseException("调用阿里云IOT平台查询失败");
        }

        // 2.将产品列表存入到redis中
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();

        // 将结果存入到Redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(productInfo));
    }

    /**
     * 从Redis中获取所有产品列表
     *
     * @return 产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        String result = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        return JSONUtil.toList(result, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto 设备数据
     */
    @Override
    public void register(DeviceDto deviceDto) {
        // 1.判断设备名称是否重复，如果重复，结束
        Long count = deviceMapper
                .selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }

        // 2.调用IOT平台接口新增设备
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        RegisterDeviceResponse registerDeviceResponse;
        try {
            registerDeviceResponse = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("调用IOT平台添加设备失败");
        }

        if (!registerDeviceResponse.getBody().success) {
            throw new BaseException("调用IOT平台添加设备失败");
        }

        // 3.补全iot_id到设备对象中
        deviceDto.setIotId(registerDeviceResponse.getBody().getData().getIotId());

        // 4.调用IOT平台接口获取产品名称
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new BaseException("调用IOT平台添获取产品失败");
        }

        if (!queryProductResponse.getBody().success) {
            throw new BaseException("调用IOT平台添获取产品失败");
        }

        // 5.将产品名称保存到设备对象中
        deviceDto.setProductName(queryProductResponse.getBody().getData().getProductName());

        // 6.判断位置类型是否为0，为0是随身设备，更改设备物理位置为-1
        if (deviceDto.getLocationType() == 0) {
            // 随身设备
            deviceDto.setPhysicalLocationType(-1);
        }

        try {
            // 7.保存设备对象到数据库中
            Device device = new Device();
            BeanUtils.copyProperties(deviceDto, device);
            save(device);
        } catch (Exception e) {
            // 如果保存失败，删除物联网平台上的设备数据
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setIotId(deviceDto.getIotId());
            deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
            deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

            DeleteDeviceResponse deleteDeviceResponse;
            try {
                deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
                if (!deleteDeviceResponse.getBody().success) {
                    throw new BaseException("调用IOT平台删除设备失败");
                }
            } catch (Exception ex) {
                throw new BaseException("调用IOT平台删除设备失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 查询设备详情
     *
     * @param deviceDto 设备信息
     * @return 设备详情
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        // 1.根据产品和设备查询IOT平台获取设备详情
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryDeviceDetailRequest.setIotId(deviceDto.getIotId());
        queryDeviceDetailRequest.setProductKey(deviceDto.getProductKey());

        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台添获取产品失败");
        }
        // 从response中获取想要的数据
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();

        // 2.根据设备iotid获取数据库表中的设备信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, deviceDto.getIotId()));

        // 3.合并数据
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().setIgnoreNullValue(true));

        // 4.返回数据
        return deviceVo;
    }

    /**
     * 查看指定产品的已发布的物模型的功能定义详情
     *
     * @param deviceDto 设备信息
     * @return 物模型数据
     */
    @Override
    public AjaxResult queryThingModelPublished(DeviceDto deviceDto) {
        QueryThingModelPublishedRequest request = new QueryThingModelPublishedRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());

        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台添获取产品物模型失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询物模型运行状态
     *
     * @param request 请求参数
     * @return 结果
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台获取设备物模型运行状态失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceNickName(Device device) {
        // 1.修改数据库中的信息
        updateById(device);

        // 2.修改IOT平台中的数据
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list = new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo deviceNickNameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        // 封装条件数据
        deviceNickNameInfo.setIotId(device.getIotId());
        deviceNickNameInfo.setNickname(device.getNickname());
        list.add(deviceNickNameInfo);

        request.setDeviceNicknameInfo(list);

        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().getSuccess()) {
            throw new BaseException("调用IOT平台修改设备备注失败");
        }
    }

    /**
     * 删除设备信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteDevice(DeleteDeviceRequest request)
    {
        // 通过设备id删除设备
        remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,request.getIotId()));
        // 删除物联网中的数据
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("IOT调用，删除设备失败");
        }

        if(!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return 1;
    }
}
